﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;

#if !NET40

namespace System.Threading
{
    // very naive implementation of .net 4.0 cancellation token pattern

    public struct CancellationToken
    {
        public static CancellationToken None
        {
            get { return default(CancellationToken); }
        }

        public bool IsCancellationRequested
        {
            get { return CancellationTokenSource != null && CancellationTokenSource.IsCancellationRequested; }
        }

        public void ThrowIfCancellationRequested()
        {
            if (IsCancellationRequested)
                throw new OperationCanceledException();
        }

        private CancellationTokenSource CancellationTokenSource { get; set; }


        internal CancellationToken(CancellationTokenSource cts)
            : this()
        {
            CancellationTokenSource = cts;
        }
    }


    public class CancellationTokenSource
    {
        public CancellationToken Token
        {
            get { return new CancellationToken(this); }
        }

        public bool IsCancellationRequested
        {
            get;
            private set;
        }

        public void Cancel()
        {
            IsCancellationRequested = true;
        }
    }
}

#endif